import Vue from 'vue'

import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/login'
  // 重定向路由
}, {
  path: '/login',
  component: Login
  // 根据路由渲染组件
}, {
  path: '/home',
  component: Home
}]

const router = new VueRouter({
  routes
})

// 挂载一个路由导航守卫
router.beforeEach((to, from, next) => {
  // to：将要访问的路径
  // from：从哪个路径跳转而来，这个指的是非登录页
  // next：放行函数
  //    next()  直接放行  next('/login')  强制跳转回登录页
  if (to.path === '/login') return next()
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
